package com.example.demo.Controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.QueryPageParam;
import com.example.demo.common.Result;
import com.example.demo.entity.Adoption;
import com.example.demo.entity.Notification;
import com.example.demo.entity.Search;
import com.example.demo.entity.User;
import com.example.demo.service.INotificationService;
import com.example.demo.service.ISearchService;
import com.example.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author demo
 * @since 2025-02-28
 */
@RestController
@RequestMapping("/search")
public class SearchController {
    @Autowired
    private IUserService userService;
    @Autowired
    private ISearchService searchService;
    @Autowired
    private INotificationService notificationService;
    //新增
    @PostMapping("/save")
    public Result save(
            @RequestParam("petName") String petName,
            @RequestParam("loseType") String loseType,
            @RequestParam("content") String content,
            @RequestParam("location") String location,
            @RequestParam("loseTime") @DateTimeFormat
                    (pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime loseTime,
            @RequestParam("ownerNo") String ownerNo,
            @RequestParam("phoneNum") String phoneNum,
            @RequestParam("status") Integer status ,
            @RequestParam(value = "imageFile", required = false) MultipartFile imageFile,
            HttpServletRequest request /*添加请求参数*/){


        Search search = new Search();
        search.setPetName(petName);
        search.setLoseType(loseType);
        search.setContent(content);
        search.setLocation(location);
        search.setLoseTime(loseTime);
        search.setOwnerNo(ownerNo);
        search.setPhoneNum(phoneNum);
        search.setStatus(status);
        System.out.println("Received parameters: ");
        System.out.println("petName: " + petName);
        System.out.println("loseType: " + loseType);
        System.out.println("content: " + content);
        System.out.println("loseTime: " + loseTime);
        if (imageFile != null && !imageFile.isEmpty()) {
            try {
                // 校验文件大小
                if (imageFile.getSize() > 2 * 1024 * 1024) {
                    return Result.fail("文件大小超过2M");
                }
                //图片类型校验
                String contentType = imageFile.getContentType();
                if (!Arrays.asList("image/jpeg", "image/png").contains(contentType)) {
                    return Result.fail("仅支持JPEG/PNG格式");
                }
                search.setPetImage(imageFile.getBytes());
                search.setImageType(contentType);
            } catch (IOException e) {
                return Result.fail("文件处理失败");
            }
        }

        boolean saveResult = searchService.save(search);
        return saveResult ? Result.suc() : Result.fail("数据库保存失败");
    }
    //更新
    @PostMapping("/update")
    public Result update(@RequestBody Search search){
        return searchService.updateById(search)?Result.suc():Result.fail();
    }

    //删除
    @GetMapping("/del")
    public Result del(@RequestParam Long id){
        return searchService.removeById(id)?Result.suc():Result.fail();
    }

    //图片获取接口
    @GetMapping("/image/{id}")
    public void getImage(@PathVariable Long id, HttpServletResponse response)throws IOException {
        Search search = searchService.getById(id);
        if (search == null || search.getPetImage() == null) {
            response.sendError(404, "Image not found");
            return;
        }
        String contentType = search.getImageType();
        response.setContentType(contentType != null ? contentType : "image/jpeg");
        response.getOutputStream().write(search.getPetImage());

    }

    //图片上传接口
    @PostMapping("/uploadImage")
    public Result uploadImage(@RequestParam("file") MultipartFile file,
                              @RequestParam String searchId)
            throws IOException{
        if (file.isEmpty()) {
            return Result.fail();
        }
        if (!Arrays.asList("image/jpeg", "image/png").contains(file.getContentType())) {
            return Result.fail();
        }
        if (file.getSize() > 2 * 1024 * 1024) {
            return Result.fail();
        }
        Search search = searchService.getById(searchId);
        if (search == null) {
            return Result.fail();
        }
        //直接存储二进制数据，文件类型
        search.setImageType(file.getContentType());
        search.setPetImage(file.getBytes());
        //更新用户数据
        return searchService.updateById(search) ? Result.suc() : Result.fail();
    }

    @PostMapping("/listPageS")
    public Result listPageS(@RequestBody QueryPageParam query) {
        HashMap param = query.getParam();
        String keywords = (String)param.get("keywords");

        Page<Search> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<Search> lambdaQueryWrapper = new LambdaQueryWrapper();
        if (StringUtils.isNotBlank(keywords) && !"null".equals(keywords)){
            lambdaQueryWrapper.and(wrapper ->
                    wrapper.like(Search::getPetName, keywords)
                            .or()
                            .like(Search::getLocation, keywords)
                            .or()
                            .like(Search::getOwnerNo, keywords)
            );
        }
        System.out.println("查询条件: " + lambdaQueryWrapper.getCustomSqlSegment());
        IPage result = searchService.pageS(page,lambdaQueryWrapper);
        List<Search> records = result.getRecords();
        return  Result.suc(records,result.getTotal());

    }

    // 标记:已找到接口
    @PostMapping("/markFound/{id}")
    public Result markFound(@PathVariable Long id) {
        Search search = searchService.getById(id);
        if (search == null) {
            return Result.fail("记录不存在");
        }
        search.setStatus(1); // 1表示已提交取消申请
        searchService.updateById(search);

        String ownerNo = search.getOwnerNo();
        String petName = search.getPetName();

        // 创建通知内容
        String content = String.format(
                "用户（%s）提交了宠物【%s】的已找到申请（ID: %s）",
                ownerNo, petName, id
        );

        List<User> admins = userService.lambdaQuery()
                .in(User::getRoleId, Arrays.asList(0, 1))
                .list();

        for (User admin : admins) {
            Notification notification = new Notification();
            notification.setType(0); // 寻宠类通知
            notification.setUserId(admin.getNo()); // 使用管理员的账号
            notification.setContent(content);
            notification.setStatus(0);
            notification.setCreateTime(LocalDateTime.now());
            notification.setRelatedId(id);
            notificationService.save(notification);
        }

        return Result.suc("已提交申请到后台");
    }

    // 管理员处理取消申请
    @PostMapping("/processCancel/{id}")
    public Result processCancel(@PathVariable Long id) {
        return searchService.removeById(id) ? Result.suc() : Result.fail();
    }

    @PostMapping("/markProcessed/{id}")
    public Result markProcessed(@PathVariable Long id) {
        Search search = searchService.getById(id);
        if (search == null) {
            return Result.fail("记录不存在");
        }
        search.setStatus(2); // 2表示已处理
        return searchService.updateById(search) ? Result.suc() : Result.fail();
    }

}
